<template>
    <div>
        <el-form ref="form" label-width="80px" :model="spu">
            <el-form-item label="SPU名称">
                <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
            </el-form-item>
            <el-form-item label="品牌">
                <el-select placeholder="请选择品牌" v-model="spu.tmId">
                    <el-option :label="trade.tmName" :value="trade.id" v-for="(trade, index) in tradeMarkList"
                        :key="trade.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input type="textarea" rows="4" placeholder="描述" v-model="spu.description"></el-input>
            </el-form-item>
            <el-form-item label="SPU图片">
                <el-upload action="/dev-api/admin/product/fileUpload" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="spuImageList"
                    :on-success="handleSuccess">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form-item>
            <el-form-item label="销售属性">
                <el-select :placeholder="`还有${unSelectSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
                    <el-option :label="sale.name" :value="`${sale.id}:${sale.name}`"
                        v-for="(sale, index) in unSelectSaleAttr" :key="sale.id">
                    </el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-plus" :disabled="!attrIdAndAttrName"
                    @click="addSaleAttr">添加销售属性</el-button>
                <el-table style="width: 100%; margin: 15px 0" border :data="spu.spuSaleAttrList">
                    <el-table-column type="index" label="序号" width="80" align="center">
                    </el-table-column>
                    <el-table-column prop="saleAttrName" label="属性名" width="160">
                    </el-table-column>
                    <el-table-column prop="prop" label="属性值名称列表">
                        <template slot-scope="{row, $index}">
                            <el-tag :key="tag.id" v-for="(tag, index) in row.spuSaleAttrValueList" closable
                                :disable-transitions="false" @close="row.spuSaleAttrValueList.splice(index, 1)">
                                {{ tag.saleAttrValueName }}
                            </el-tag>
                            <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue"
                                ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(row)"
                                @blur="handleInputConfirm(row)">
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small"
                                @click="addSaleAttrValue(row)">添加</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="prop" label="操作" width="160">
                        <template slot-scope="{row, $index}">
                            <el-button size="mini" type="danger" icon="el-icon-delete"
                                @click="spu.spuSaleAttrList.splice($index, 1)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" @click="addOrUpdateSpu()">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
export default {
    nama: 'SpuForm',
    data() {
        return {
            dialogImageUrl: '',
            dialogVisible: false,
            spu: {
                category3Id: 0,
                description: "",
                id: 0,
                spuImageList: [
                    // {
                    //     id: 0,
                    //     imgName: "",
                    //     imgUrl: "",
                    //     spuId: 0
                    // }
                ],
                spuName: "",
                spuSaleAttrList: [
                    // {
                    //     baseSaleAttrId: 0,
                    //     id: 0,
                    //     saleAttrName: "",
                    //     spuId: 0,
                    //     spuSaleAttrValueList: [
                    //         {
                    //             baseSaleAttrId: 0,
                    //             id: 0,
                    //             isChecked: "",
                    //             saleAttrName: "",
                    //             saleAttrValueName: "",
                    //             spuId: 0
                    //         }
                    //     ]
                    // }
                ],
                tmId: ''
            },// 存储spu信息属性
            tradeMarkList: [],// 存储品牌信息
            spuImageList: [], //存出spu图片的数组
            saleAttrList: [],// 平台销售属性列表
            attrIdAndAttrName: '',//收集未选择的销售属性的id+销售属性名称
        }
    },
    methods: {
        // 照片墙删除某一个照片的时候会触发
        handleRemove(file, fileList) {
            // file: 删除的那一张图
            // fileList: 照片墙删除图片后剩下的图片数据
            // console.log(file, fileList);
            this.spuImageList = fileList
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        // 图片上传成功
        handleSuccess(response, file, fileList) {
            this.spuImageList = fileList
        },
        // 初始化数据
        async initSpuData(spu) {
            let res = await this.$API.spu.reqSpu(spu.id)
            if (res.code == 200) {
                this.spu = res.data
            }
            let res2 = await this.$API.spu.reqTradeMarkList()
            if (res2.code == 200) {
                this.tradeMarkList = res2.data
            }
            let res3 = await this.$API.spu.reqSpuImageList(spu.id)
            if (res3.code == 200) {
                let listArr = res3.data
                // 由于照片墙数组，且数组里面的元素需要name和url字段，所以需要把返回的数据进行修改
                listArr.forEach(item => {
                    item.name = item.imgName
                    item.url = item.imgUrl
                });
                this.spuImageList = listArr
            }
            let res4 = await this.$API.spu.reqBaseSaleAttr()
            if (res4.code == 200) {
                this.saleAttrList = res4.data
            }
        },
        // 添加新的销售属性
        addSaleAttr() {
            const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":")
            let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
            this.spu.spuSaleAttrList.push(newSaleAttr)
            this.attrIdAndAttrName = ''
        },
        // 添加属性值
        addSaleAttrValue(row) {
            this.$set(row, 'inputVisible', true)
            this.$set(row, 'inputValue', '')
        },
        // 
        handleInputConfirm(row) {
            const { baseSaleAttrId, inputValue } = row
            if (inputValue.trim() == '') {
                this.$message("属性值不能为空")
                return
            }
            let result = row.spuSaleAttrValueList.every(item => item.saleAttrValueName != inputValue)
            if (!result) {
                this.$message("属性值不能重复")
                return
            }
            let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue }
            row.spuSaleAttrValueList.push(newSaleAttrValue)
            row.inputVisible = false
        },
        async addOrUpdateSpu() {
            this.spu.spuImageList = this.spuImageList.map(item => {
                return {
                    imgName: item.name,
                    imgUrl: (item.response ? item.response.data : item.url)
                }
            })
            let res = await this.$API.spu.reqAddOrUpdateSpu(this.spu)
            if (res.code == 200) {
                this.$message({ type: 'success', message: '保存成功' })

                this.$emit('changeScene', { scene: 0, flag: this.spu.id ? '修改' : '添加' })
            }
            Object.assign(this._data, this.$options.data())
        },
        async addSpuData(category3Id) {
            this.spu.category3Id = category3Id
            let res2 = await this.$API.spu.reqTradeMarkList()
            if (res2.code == 200) {
                this.tradeMarkList = res2.data
            }
            let res4 = await this.$API.spu.reqBaseSaleAttr()
            if (res4.code == 200) {
                this.saleAttrList = res4.data
            }
        },
        cancel() {
            this.$emit('changeScene', { scene: 0, flag: '' })
            // 组件实例this._data,可以操作data当中的响应式数据
            // this.$options可以获取配置对象,配置对象的data函数执行，返回响应式数据为空
            Object.assign(this._data, this.$options.data())
        }
    },
    computed: {
        unSelectSaleAttr() {
            return this.saleAttrList.filter(item => {
                // 过滤出用户需要的元素
                return this.spu.spuSaleAttrList.every(item1 => {
                    // every返回布尔值
                    return item.name != item1.saleAttrName
                })
            })
        }
    }
}
</script>

<style>
.el-tag+.el-tag {
    margin-left: 10px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>